<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { ElTable, FormInstance } from "element-plus"
import { sizeDate, shortcuts } from "@/utils/dateSet"
import { formatDateTime } from "@/utils"
import { useRouter } from "vue-router"

// 接口
import { getTyList, getItemizedList, downLoadTable } from "@/api/SZ/SzGeneral"
import { getqueryTeamName } from "@/api/SZ/SZXxfy"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh, Download } from "@element-plus/icons-vue"
const router = useRouter()
const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "SzGeneral"
})
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]
const shopList = ref<any>([])
const typeList = ref<any>([
  {
    label: "汇总表",
    value: 1
  },
  {
    label: "明细表",
    value: 2
  }
])

/**店铺数据 */
const getShopList = () => {
  getqueryTeamName().then((res: any) => {
    if (res.code == 200) {
      shopList.value = res.data
      // console.log(res)
    }
  })
}
getShopList()
//清除查询日期
const clearDate = (val: any) => {
  // console.log(val)
  if (!val) {
    searchData.searchDate = []
  }
}

// #region 查
const columns = ref<any>([
  // {
  //   label: "查询链接",
  //   children: [
  //     { label: "活动明细", prop: "hdmx" },
  //     { label: "线下明细", prop: "xxmx" },
  //     { label: "充值明细", prop: "cxmx" },
  //     { label: "链接明细", prop: "ljmx" }
  //   ]
  // }
])
const tableTotal = ref<number>()
const tableData = ref<any[]>([])
const tableDataPeople = ref<any[]>([])
const getList = () => {
  loading.value = true
  getTyList({
    shopName: searchData.shopName.name,
    shopId: searchData.shopName.id,
    type: searchData.type,
    startTime:
      searchData.searchDate && searchData.searchDate.length ? new Date(searchData?.searchDate[0]).getTime() : "",
    endTime: searchData.searchDate && searchData.searchDate.length ? new Date(searchData?.searchDate[1]).getTime() : ""
  })
    .then((res: any) => {
      tableData.value = res.data.data || []
      tableDataPeople.value = res.data.people || []
      columns.value = res.data.head

      // tableTotal.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      tableData.value = []
      loading.value = false
    })
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const now = new Date()
const searchData = reactive<any>({
  shopName: "",
  searchDate: [
    new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0),
    new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 23, 59, 59)
  ],
  type: 1
})
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getList()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getList()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
// #endregion

// 颜色数组，循环分配给一级表头
const colorList = ref<any>([
  "#FFC107", // 黄色
  "#00CED1", // 青色
  "#32CD32", // 绿色
  "#FF4500", // 红色
  "#FFD700", // 金色
  "#1E90FF" // 蓝色
])
// 单元格颜色数组，与表头颜色不同
const cellColorList = ref<any>([
  "#E6E6FA", //  - 销售统计
  "#f2f3f5", //  - 占比分析（占位，实际动态变化）
  "#CCE5FF", //  - 收入项目
  "#ebd0d0", //  - 费用项目
  "#fcf8e3", // - 利润分析
  "#dff0d8" // - 查询链接
])
// 动态设置表头颜色
const headerCellStyle = ({ column, rowIndex }: any) => {
  if (rowIndex === 0) {
    // 根据一级表头的索引生成类名
    const headerIndex = columns.value.findIndex((col: any) => col.label === column.label)
    if (headerIndex !== -1) {
      return { background: colorList.value[headerIndex], color: "#000" }
    }
  }
  return {}
}
// 动态设置单元格颜色
const cellStyle = ({ row, column }: any) => {
  // 找到当前列所属的一级表头
  let parentHeaderLabel = ""
  for (const col of columns.value) {
    if (col.children.some((child: any) => child.prop === column.property)) {
      parentHeaderLabel = col.label
      break
    }
  }

  // 根据一级表头设置单元格颜色
  const headerIndex = columns.value.findIndex((col: any) => col.label === parentHeaderLabel)
  if (headerIndex === -1) {
    // 日期列（manageTime）
    return { background: "#dff0d8" }
  }

  // 特殊处理“占比分析”区域的单元格颜色（基于数值）
  if (parentHeaderLabel === "占比分析") {
    const value = row[column.property]
    // 假设占比分析的值是百分比字符串（如 "70.5%"），需要提取数值
    const numericValue = typeof value === "string" && value.includes("%") ? parseFloat(value.replace("%", "")) : value
    if (typeof numericValue === "number") {
      if (numericValue >= 70) {
        return { background: "#90EE90" } // 绿色
      } else if (numericValue >= 50) {
        return { background: "#FFFF99" } // 黄色
      } else {
        // return { background: "#FF6347" } // 红色
      }
    }
  }

  // 其他区域的单元格使用 cellColorList 中的颜色
  return { background: cellColorList.value[headerIndex] }
}
//充值明细
const dialogVisibleRotation = ref(false)
const tableRotation = ref<any>([])
const seeDetails = (row: any) => {
  tableRotation.value = []
  dialogVisibleRotation.value = true
  loading.value = true
  getItemizedList({
    shopName: searchData.shopName.name,
    shopId: searchData.shopName.id,
    startTime: new Date(row.dates).getTime(),
    endTime: new Date(row.dates).getTime()
  })
    .then((res: any) => {
      if (res.code == 200) {
        tableRotation.value = res.data
        console.log(res)
      }
    })
    .finally(() => {
      loading.value = false
    })
}
/**字段解释 */
const dialogVisibleword = ref(false)
const tableWrod = ref<any>([
  {
    word: "总录单",
    detail: "筛选条件下的：凡思特订单总数"
  },
  {
    word: "发货数",
    detail: "筛选条件下的：凡思特订单状态》（已激活+受理成功+处理中+待处理）"
  },
  {
    word: "已激活",
    detail: "筛选条件下的：凡思特订单状态》（已激活）"
  },
  {
    word: "已结佣",
    detail: "筛选条件下的：凡思特结佣状态》（已结佣）"
  },
  { word: "废单量", detail: "筛选条件下的：凡思特结佣状态》（废单量）" },
  { word: "处理中", detail: "筛选条件下的：凡思特结佣状态》（处理中）" },
  { word: "受理成功", detail: "筛选条件下的：凡思特结佣状态》（受理成功）" },
  { word: "受理失败", detail: "筛选条件下的：凡思特结佣状态》（受理失败）" },
  { word: "下单数", detail: "天猫店铺：生意参谋的支付买家数，拼多多店铺：下订单，京东店铺：下单数" },
  { word: "退单数", detail: "天猫店铺：无退单数，拼多多店铺：退单数，京东店铺：退单数" },
  { word: "占录单发货率", detail: "同字义" },
  { word: "占录单激活率", detail: "同字义" },
  { word: "占发货激活率", detail: "同字义" },
  { word: "占结佣激活率", detail: "同字义" },
  {
    word: "平台收入",
    detail: "天猫店铺：生意参谋的支付金额；拼多多店铺：拼多多商家后台的当日收入；京东：京东商智的收入"
  },
  { word: "退款金额", detail: "平台的退款金额" },
  {
    word: "预估佣金",
    detail:
      "佣金收入：当日的（已激活+受理成功+处理中）订单的套餐的佣金*当日实时激活率(最近7天的激活率向前递延14天所得，例如：7.31日用的是7.17日当天的激活率)*0.8"
  },
  {
    word: "推广费用",
    detail:
      "天猫店铺：生意参谋的直通车、引力魔方、万相台、淘宝客、号卡金额、投卡宝；拼多多店铺：拼多多商家后台的推广费+保证金退款；京东：京东商智的推广费"
  },
  { word: "直通车", detail: "生意参谋》整体看板》直通车花费" },
  { word: "引力魔方", detail: "生意参谋》整体看板》引力魔方花费" },
  { word: "万相台", detail: "生意参谋》整体看板》万相台花费" },
  { word: "淘宝客", detail: "生意参谋》整体看板》淘宝客佣金" },
  { word: "支付买家数", detail: "生意参谋》整体看板》支付买家数" },
  { word: "号卡金额", detail: "商家中心》资金账户》号卡中心" },
  { word: "投卡宝", detail: "商家中心》资金账户》投卡宝" },
  { word: "活动费用", detail: "活动本金+活动本金大额+活动佣金+活动邮费" },
  { word: "线下费用", detail: "赔偿费用+返卡费差价+话费补贴+激活奖励+其他支出" },
  { word: "投诉罚款", detail: "运营商有责*500+工商有责*500+超时处罚*50" },
  { word: "话费充值", detail: "凡思特手动充值部分" },
  { word: "链接话费", detail: "客户自主通过店铺链接领取" },
  {
    word: "管理费用",
    detail:
      "京东：（成交单量-宽带数）*（2024-10-01之前佣金费用为8元每单，之后为45元每单）*0.96 (赵鹏辉制定参数)；拼多多：保证金退款"
  },
  { word: "预估人工", detail: "单日人数*单人支出+特殊参数+录单量*单卡奖金" },
  {
    word: "冻结话费",
    detail:
      "各订单的是店铺链接的月数*月返*当日激活率(最近7天的激活率向前递延14天所得，例如：7.31日用的是7.17日当天的激活率)*0.6"
  },
  { word: "预估税费", detail: "预估佣金*0.06+ （收入-退款）*0.06（天猫和京东按照0.09）" },
  { word: "预估利润", detail: "收入项目-费用项目" },
  { word: "卡均利润", detail: "（收入项目-费用项目）/(已激活+受理成功+处理中)" },
  { word: "人均利润", detail: "（收入项目-费用项目）/单日人数" },
  {
    word: "卡均佣金",
    detail:
      "筛选条件下的：(已激活+受理成功+处理中)状态的订单的套餐适配的佣金政策金额合计/(已激活+受理成功+处理中)状态的订单数"
  },
  { word: "宽带数", detail: "'已完成', '处理中', '安装中' 三种状态的订单数(注释：和凡思特正常订单的数据不搅合)" },
  {
    word: "宽带佣金",
    detail:
      "'已完成', '处理中', '安装中' 三种状态的订单的预计结佣金额，未考虑结佣率，目前只做展示，还未提现到利润算法里面。"
  },
  {
    word: "预估激活佣金",
    detail: "佣金收入：当日的（已激活）订单的套餐的佣金*0.8*0.8"
  },
  {
    word: "按激活卡均佣金",
    detail: "筛选条件下的：(已激活)状态的订单的套餐适配的佣金政策金额合计/(已激活)状态的订单数"
  }
])
const wordEffect = () => {
  dialogVisibleword.value = true
}
/**线下费用跳转 */
const OfflineTo = (row: any) => {
  console.log(row)
  router.push(`/SZ/SZXxfy?start=${new Date(row.dates).getTime()}&shop=${row.shopId}`)
}
/**活动费用跳转 */
const activeTo = (row: any) => {
  console.log(row)
  router.push(`/SZ/SZHdfy?start=${new Date(row.dates).getTime()}&shop=${row.shopId}`)
}
// #region 下载
const downLoad = () => {
  downLoadTable({
    ...searchData,
    startTime: new Date(searchData.searchDate[0]).getTime() || "", // 时间
    endTime: new Date(searchData.searchDate[1]).getTime() || "" // 时间
  }).then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "收支通用.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
  })
}
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getList, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="searchDate" label="日期">
          <el-date-picker
            v-model="searchData.searchDate"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :size="sizeDate"
            :default-time="defaultTime1"
            @change="clearDate"
          />
        </el-form-item>
        <el-form-item prop="shopName" label="店铺">
          <el-select v-model="searchData.shopName" clearable filterable placeholder="请选择" value-key="id">
            <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item prop="type" label="类型">
          <el-select v-model="searchData.type" clearable filterable placeholder="请选择">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>

          <el-button type="primary" :icon="Download" circle @click="downLoad" />
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 中间渲染内容 -->
      <div class="table-center" v-horizontal-scroll="'always'">
        <div class="btn" style="padding-bottom: 10px">
          <el-button @click="wordEffect">字段解释</el-button>
        </div>
        <el-table :data="tableData" :header-cell-style="headerCellStyle" :cell-style="cellStyle">
          <el-table-column label="日期" align="center" prop="dates" width="180" />
          <!-- 动态渲染一级表头 -->
          <template v-for="(column, index) in columns" :key="index">
            <el-table-column :label="column.label" align="center">
              <!-- 动态渲染二级表头 -->
              <template v-for="(subColumn, subIndex) in column.children" :key="subIndex">
                <el-table-column :prop="subColumn.prop" :label="subColumn.label" align="center">
                  <template #default="scope">
                    <template
                      v-if="
                        subColumn.prop === 'fhl' ||
                        subColumn.prop === 'jhl' ||
                        subColumn.prop === 'zfhjhl' ||
                        subColumn.prop === 'kdjgl'
                      "
                    >
                      <el-progress
                        :text-inside="true"
                        status="success"
                        :stroke-width="18"
                        :percentage="scope.row[subColumn.prop]"
                      />
                    </template>
                    <template v-if="subColumn.prop === 'czmxs' && scope.row[subColumn.prop]">
                      <el-button type="primary" @click="seeDetails(scope.row)">{{
                        scope.row[subColumn.prop]
                      }}</el-button>
                    </template>
                    <template v-if="subColumn.prop === 'xxmxs' && scope.row[subColumn.prop]">
                      <el-button type="primary" @click="OfflineTo(scope.row)">{{
                        scope.row[subColumn.prop]
                      }}</el-button>
                    </template>
                    <template v-if="subColumn.prop === 'hdmxs' && scope.row[subColumn.prop]">
                      <el-button type="primary" @click="activeTo(scope.row)">{{ scope.row[subColumn.prop] }}</el-button>
                    </template>
                  </template>
                </el-table-column>
              </template>
            </el-table-column>
          </template>
          <!-- <el-table-column label="查询链接" align="center" prop="dates" width="180">
            <el-table-column label="凡思特充值" align="center">
              <template #default="scope">
                <el-button type="primary" @click="seeDetails(scope.row)">明细</el-button>
              </template>
            </el-table-column>
          </el-table-column> -->
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination" style="display: none">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :page-size="paginationData.pageSize"
          :total="tableTotal"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="table-center" v-horizontal-scroll="'always'" v-if="tableDataPeople.length">
        <el-table :data="tableDataPeople">
          <el-table-column label="执行时间" align="center" prop="manageTime" />
          <el-table-column label="人数" align="center" prop="dailyHeadcount" />
          <el-table-column label="财务人员" align="center" prop="finance" />
          <el-table-column label="运营人员" prop="headList" width="1000" />
        </el-table>
      </div>
      <el-dialog v-model="dialogVisibleRotation" title="充值明细" center>
        <el-scrollbar height="600px">
          <el-table :data="tableRotation" v-loading="loading">
            <el-table-column prop="id" label="订单号" align="center" />
            <el-table-column prop="overview" label="交易概述" align="center" />
            <el-table-column prop="date" label="交易时间" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="交易金额" align="center" />
            <el-table-column prop="balance" label="账户余额" align="center" />
            <el-table-column prop="user" label="交易账号" align="center" />
            <el-table-column prop="note" label="交易备注" align="center" />
          </el-table>
        </el-scrollbar>
      </el-dialog>
      <el-dialog v-model="dialogVisibleword" title="字段解释" center width="80%">
        <el-scrollbar height="600px">
          <el-table :data="tableWrod" v-loading="loading">
            <el-table-column prop="word" label="字段" width="150" />
            <el-table-column prop="detail" label="解释" />
          </el-table>
        </el-scrollbar>
      </el-dialog>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.middle-top {
  margin-bottom: 20px;
}
.table-center {
  margin-bottom: 20px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-progress-bar__innerText) {
  color: #333;
}
:deep(.el-table .cell) {
  padding: 0;
}
:deep(.el-scrollbar__bar.is-horizontal) {
  height: 12px;
  left: 1px;
}
:deep(.el-scrollbar__bar) {
  position: absolute;
  right: 1px;
  bottom: 1px;
  z-index: 1;
  border-radius: 8px;
  background-color: #d3d3d3;
}
:deep(.el-card__body) {
  padding: 10px 20px 0px 20px;
}
</style>
